package cn.jsc.consumer;

import cn.jsc.constants.BaseConstants;
import cn.jsc.dto.EmailDto;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;

/**
 * @description: 消费者
 */
@Component
@Slf4j
public class MessageConsumer {

    //发送短信
    @RabbitListener(queues = {BaseConstants.RabbitMQConstants.QUEUE_NAME_SMS})
    public void handlerSMSMessage(String content, Message message, Channel channel) {
        log.info("监听短信队列，收到消息：{}", content);
        //调用第三方接口，发送短信操作
        //.......

        //手动签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("发送短信，签收失败：" + e);
        }
    }

    //发送邮件
    @RabbitListener(queues = {BaseConstants.RabbitMQConstants.QUEUE_NAME_EMAIL})
    public void handlerEmailMessage(String content, Message message, Channel channel) throws IOException, InterruptedException {
        log.info("监听邮件队列，收到消息：{}", content);
        EmailDto dto = JSONObject.parseObject(content, EmailDto.class);
        //业务逻辑：发送邮件，调用网关接口
        List<String> emailAddress = dto.getEmailAddress();
        for (int i = 0; i < emailAddress.size(); i++) {
            log.info("调用第三方接口发送邮件，收件箱={}", emailAddress.get(i));
        }
        //设置睡眠3秒
        Thread.sleep(3000);
        //手动ack签收消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //发送站内信
    @RabbitListener(queues = {BaseConstants.RabbitMQConstants.QUEUE_NAME_STATION})
    public void handlerStationMessage(String content, Message message, Channel channel) {
        System.out.println("发送站内信：" + content);
        //保存信息到数据库
        //.......

        //手动签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("发送站内信，签收失败：" + e);
        }
    }
}